/**
 * Copyright (C), 2012-2018, 联奕科技有限公司
 * FileName: QQImpl
 * Author:   石贵武
 * Date:     2018\3\13 0013 19:01
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.zhoudongxiu.security.core.social.qq.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;
import java.text.Format;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author 石贵武
 * @create 2018\3\13 0013
 * @since 1.0.0
 */
@Slf4j
public class QQImpl extends AbstractOAuth2ApiBinding implements  QQ {

    private final static String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";

    private final static String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";

    private String appId;

    private String openId;

    private ObjectMapper objectMapper = new ObjectMapper();


    public QQImpl(String access_Token, String appId) {
        super(access_Token, TokenStrategy.ACCESS_TOKEN_PARAMETER);
        this.appId = appId;
        log.info("请求开始，获取openid");
        String url = String.format(URL_GET_OPENID, access_Token);
        String result = getRestTemplate().getForObject(url, String.class);
        log.info("获取openid的请求结果为: result={}", result);
        this.openId = StringUtils.substringBetween(result, "\"openid\":", "}");

    }

    @Override
    public QQUserInfo getUserInfo() {

        String url = String.format(URL_GET_USERINFO, appId, openId);
        String result = getRestTemplate().getForObject(url, String.class);
        log.info("请求到用户信息的结果为:result={}", result);

        try {
            return objectMapper.readValue(result, QQUserInfo.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("获取用户信息失败!!!");
        }

    }
}